<template>
  <el-card>
    <!--添加品牌按钮-->
    <el-button type="primary" size="default" style="width: 80px" icon="Plus" @click="showDialog">新增</el-button>
    <el-table style="margin: 10px 0" border :data="tradeMarkList">
      <el-table-column label="序号" type="index" width="80" align="center" />
      <!-- <el-table-column label="品牌名称" prop="tmName" /> -->
      <!-- 支持插槽 -->
      <el-table-column label="品牌名称">
        <template #default="{ row }">
          <el-tag>{{ row.tmName }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="品牌LOGO">
        <template #default="{ row }">
          <img :src="row.logoUrl" style="width: 80px; height: 80px" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="warning" icon="edit" circle @click="updateTradeMark(row)"></el-button>
          <el-popconfirm
            :title='`您确定要删除${row.tmName}吗？`'
            width="260px"
            icon="Delete"
            @confirm="removeTradeMark(row.id)"
          >
            <template #reference>
              <el-button type="danger" icon="delete" circle></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 
     v-model:page-sizes：用于设置下拉菜单数据 
     background：用于设置分页器背景颜色
     layout：用于设置分页器布局
    -->
    <el-pagination
      style="margin: 20px 0"
      :background="true"
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="pageSizes"
      layout="prev, pager, next,jumper, ->, sizes, total"
      :total="total"
    />

    <!-- 新增或者编辑表单 -->
    <el-dialog :title="form.id ? '修改品牌' : '新增品牌'" v-model="dialogFormVisible">
      <el-form style="width: 80%" :model="form" :rules="rules" ref="formRef">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input v-model="form.tmName" placeholder="请输入品牌名称" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="80px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/common/upload"
            method="post"
            :headers="headers"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button style="width: 60px" type="primary" @click="cancel">取 消</el-button>
          <el-button style="width: 60px" type="primary" @click="confirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>
<script setup lang="ts">
import { ref, onMounted, watch, reactive } from 'vue'
import { reqTradeMarkList } from '@/api/product/trademark'
import { ElMessage, ElNotification } from 'element-plus'
import type { TradeMarkListRespData, TradeMark } from '@/api/product/trademark/type'
import { useUserStore } from '@/stores/modules/user'

const pageSizes = ref<number[]>([2, 3, 5, 10, 20, 50])
// 总数据条数
const total = ref<number>(30)
// 当前页码
const pageNum = ref<number>(1)
// 每页展示多少数据
const pageSize = ref<number>(10)
const tradeMarkList = ref<TradeMark[]>([])
// 请求头
const headers = ref({ Authorization: 'Bearer ' + useUserStore().token })
// 控制新增编辑对话框展示
const dialogFormVisible = ref(false)
const formRef = ref()

// 获取已有品牌的接口封装成一个函数
const getTradeMarkList = () => {
  reqTradeMarkList(pageNum.value, pageSize.value)
    .then((res: TradeMarkListRespData) => {
      total.value = res.total
      tradeMarkList.value = res.rows
    })
    .catch((err) => {
      ElNotification.error({
        title: '错误',
        message: err.message,
      })
    })
}

const showDialog = () => {
  dialogFormVisible.value = true
  // 清空表单数据
  // form.value = { id: undefined, tmName: '', logoUrl: '' }

  // 如果form表单不存在就什么也不做；如果存在就清空表单数据及校验信息
  formRef.value?.resetFields()
}

// 收集表单数据
const form = ref<TradeMark>({
  id: undefined,
  tmName: '',
  logoUrl: '',
})

// 校验品牌名称
const validateTmName = (_: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('品牌名称位数大于等于两位'))
  }
}

// 校验品牌LOGO
const validateLogoUrl = (_: any, value: any, callback: any) => {
  // 如果图片上传
  if (value.trim().length > 0) {
    callback()
  } else {
    callback(new Error('请上传品牌LOGO'))
  }
}

const rules = reactive({
  // required 表示必需校验，会出现五角星
  // trigger 代表触发时机：blur 失去焦点；change 改变
  tmName: [{ required: true, validator: validateTmName, trigger: 'blur' }],
  logoUrl: [{ required: true, validator: validateLogoUrl, trigger: 'blur' }],
})
// 取消修改或者新增
const cancel = () => {
  dialogFormVisible.value = false
}

import { reqTradeMarkAddOrUpdate } from '@/api/product/trademark'
// 确定修改或者新增
const confirm = async () => {
  // 触发表单校验，表单校验通过，才进行后续新增或者修改操作
  await formRef.value.validate()
  const res = await reqTradeMarkAddOrUpdate(form.value)
  if (res.code === 200) {
    dialogFormVisible.value = false
    ElMessage.success({
      message: form.value.id ? '修改成功' : '添加成功',
    })

    // 获取品牌列表(如果新增品牌，回到第一页)
    if (!form.value.id) {
      pageNum.value = 1
    }
    getTradeMarkList()
  } else {
    dialogFormVisible.value = false
    ElMessage.error({
      message: form.value.id ? '修改品牌失败' : '添加品牌失败',
    })
  }
}

// 修改品牌 row 已有的品牌数据
const updateTradeMark = (row: TradeMark) => {
  // 如果form表单不存在就什么也不做；如果存在就清空表单数据及校验信息
  formRef.value?.resetFields()

  dialogFormVisible.value = true
  form.value = row
}

// 上传图片前置处理：验证图片格式
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isGIF = file.type === 'image/gif'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG && !isGIF) {
    ElNotification.error({
      title: '错误',
      message: '上传头像图片只能是 JPG 格式!',
    })
  }
  if (!isLt2M) {
    ElNotification.error({
      title: '错误',
      message: '上传头像图片大小不能超过 2MB!',
    })
  }
  return (isPNG || isJPG || isGIF) && isLt2M
}

import type { UploadResp } from '@/api/common/type'

// 上传图片成功处理：将图片地址保存到表单中
const handleAvatarSuccess = (res: UploadResp, _: any) => {
  form.value.logoUrl = res.url
  // 图片上传成功后清除图片验证信息
  formRef.value.clearValidate('logoUrl')
}

import { reqTradeMarkDelete } from '@/api/product/trademark'
// 删除品牌
const removeTradeMark = async (id: number) => {
  const res = await reqTradeMarkDelete(id)
  if (res.code !== 200) {
    ElMessage.error({
      message: '删除品牌失败',
    })
    return
  } else {
    ElMessage.success({
      message: '删除成功',
    })

    // 删除成功后重新获取品牌列表 (需要确定获取哪一页的数据)
    if (tradeMarkList.value.length === 1 && pageNum.value > 1) {
      pageNum.value--
    }

    getTradeMarkList()
  }
}

// 监听分页器数据
watch([pageNum, pageSize], () => {
  getTradeMarkList()
})

// 组件挂载时，获取已有品牌列表
onMounted(() => {
  getTradeMarkList()
})
</script>

<style>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
